import request from '../utils/request'
import { ElNotification } from 'element-plus'

class DataApi {
    path

    constructor(path) {
        this.path = path
    }

    showHandleResult(res) {
        ElNotification({
            // title: 'Success',
            message: res.message || 'Error',
            type: res.success ? 'success' : 'error'
        })
    }

    /**
     * 查询
     * @param {*} data 查询对象
     */
    query(data) {
        return request({
            url: `/${this.path}/query`,
            method: 'post',
            data
        })
    }

    /**
     * 根据ID删除
     * @param {*} id entity ID
     */
    delete(id) {
        return request({
            url: `/${this.path}/${id}`,
            method: 'delete'
        }).then(res => {
            this.showHandleResult(res)
            return Promise.resolve(res)
        })
    }

    /**
     * 批量删除
     * @param {*} data entity ID array
     */
    deleteBatch(data) {
        return request({
            // url: `/${this.path}/deleteBatch`,
            url: `/${this.path}`,
            method: 'delete',
            data
        }).then(res => {
            this.showHandleResult(res)
            return Promise.resolve(res)
        })
    }

    /**
     * 修改
     * @param {*} data entity
     */
    update(data) {
        return request({
            // url: `/${this.path}/update`,
            url: `/${this.path}`,
            method: 'put',
            data
        }).then(res => {
            this.showHandleResult(res)
            return Promise.resolve(res)
        })
    }

    /**
     * 添加
     * @param {*} data entity
     */
    add(data) {
        return request({
            // url: `/${this.path}/add`,
            url: `/${this.path}`,
            method: 'post',
            data
        }).then(res => {
            this.showHandleResult(res)
            return Promise.resolve(res)
        })
    }

    /**
     * 根据ID获取
     * @param {*} id ID
     */
    getById(id) {
        return request({
            url: `/${this.path}/${id}`,
            method: 'get'
        })
    }

    /**
     * 获取编辑，查询时的下拉列表数据
     */
    getSelectData() {
        return request({
            url: `/${this.path}/select-data`,
            method: 'get'
        })
    }

    /**
     * 通用的 fetch 方法, 用 get 方法获取数据
     * @param url
     * @param params
     */
    fetch(url, params) {
        return request({
            url,
            method: 'get',
            params
        })
    }
}

export default DataApi
